package com.edu.study.base.rest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.edu.base.common.utils.DateUtils;
import com.edu.base.common.utils.IdGen;
import com.edu.base.ums.grade.domain.ClsMemberGrade;
import com.edu.base.ums.grade.mapper.ClsMemberGradeMapper;
import com.edu.base.ums.member.domain.ClsMember;
import com.edu.base.ums.member.service.IClsMemberService;
import com.edu.study.base.lmsOrder.domain.LmsOrder;
import com.edu.study.base.lmsOrder.service.ILmsOrderService;
import com.edu.study.base.lmsOrderItem.domain.LmsOrderItem;
import com.edu.study.base.lmsOrderItem.service.ILmsOrderItemService;
import com.edu.utils.UserContextUtil;
import com.ruoyi.common.config.PayConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.AppLoginUser;
import com.ruoyi.common.utils.UUIDUtils;
import com.ruoyi.common.utils.pay.AlipayUtil;
//import com.ruoyi.common.utils.pay.WechatPayUtil;
import com.ruoyi.system.service.ISysNoticeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(tags = "支付接口")
@RestController
@RequestMapping("/api/pay")
public class AppPayController {

    @Autowired
    private ClsMemberGradeMapper clsMemberGradeMapper;
    @Autowired
    private ILmsOrderService orderService;
    @Autowired
    private ILmsOrderItemService lmsOrderItemService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private IClsMemberService memberService;
    @Autowired
    private AlipayUtil alipayUtil;

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/callback/alipay")
    public String callbackAlipay(@RequestParam Map<String, String> params) throws AlipayApiException {
        // 支付宝验签
        if (!AlipaySignature.rsaCheckV1(params, payConfig.getAli_public_key(), "UTF-8", "RSA2"))
            return "error";

        String outTradeNo = params.get("outTradeNo");
        this.changeVip(outTradeNo);

        return "success";
    }

    @Autowired
    private ISysNoticeService sysNoticeService;

    private void changeVip(String outTradeNo) {
        Date date = DateUtil.parseDate(DateUtil.formatDate(DateUtil.date()));

        LmsOrder order = new LmsOrder();
        order.setOrderSn(outTradeNo);
        List<LmsOrder> orders = orderService.selectLmsOrderList(order);
        if (CollectionUtil.isEmpty(orders)) return;

        // 获取订单信息
        LmsOrderItem lmsOrderItem = new LmsOrderItem();
        lmsOrderItem.setOrderId(orders.get(0).getId());
        List<LmsOrderItem> items = lmsOrderItemService.selectLmsOrderItemList(lmsOrderItem);

        ClsMemberGrade grade = clsMemberGradeMapper.selectClsMemberGradeById(items.get(0).getProductId());

        // 获取用户信息
        ClsMember clsMember = memberService.selectClsMemberById(orders.get(0).getMemberId());

        // 获取会员期限
        Date expireDate = clsMember.getExpireDate();
        // 判断是否已过期或未购买
        if (expireDate == null || expireDate.before(date)) {
            // 重新计算开始日期
            expireDate = date;
        }

        // 累加会员月份
        expireDate = DateUtil.offsetMonth(expireDate, grade.getMemberMonth());
        // 更新会员信息
        clsMember.setExpireDate(expireDate);
        clsMember.setHandleDate(date);
        memberService.updateClsMember(clsMember);
        // 变更购买状态
        orders.get(0).setStatus(3);
        orders.get(0).setPaymentTime(new Date());
        orderService.updateLmsOrder(orders.get(0));

        sysNoticeService.saveNotice(clsMember.getId(), "支付成功", String.format("您的购买的《%s》已支付成功", items.get(0).getProductName()));
    }

//    @ApiOperation("支付宝沙箱支付-下单")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public AjaxResult pay(@RequestBody JSONObject data) {
        AppLoginUser user = UserContextUtil.currentUser();
        LmsOrder order = this.createOrder(user.getId(), data.getString("gradeId"), data.getInteger("payType"));

        Object result = null;
        switch (data.getInteger("payType")) {
            case 1: // 支付宝支付
                result = alipayUtil.createOrder(order.getOrderSn(), order.getPayAmount());
                break;
            case 2: // 微信支付
//                WechatPayUtil.createAppOrder(amount,description);
                break;
            case 3: // 积分支付
                break;
        }

        if (result == null)
            this.changeVip(order.getOrderSn());

        return AjaxResult.success(result);
    }
//    @ApiOperation("支付宝支付-下单")
//    @GetMapping("/alipay/createOrder")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "memberId", value = "会员Id",required = true),
//            @ApiImplicitParam(name = "amount", value = "金额",required = true),
//            @ApiImplicitParam(name = "description", value = "产品描述",required = true),
//    })
//    public String createOrderForZfb(@RequestBody JSONObject data){
//       return AlipayUtil.createOrder(amount,description);
//    }

//    @ApiOperation("支付宝沙箱支付-下单")
//    @PostMapping("/alipay/sandbox/createOrder")
//    public String createSandBoxOrderForZfb(@RequestBody JSONObject data){
//        AppLoginUser user = UserContextUtil.currentUser();
//        LmsOrder order = this.createOrder(user.getId(), data.getString("gradeId"), 1);
//        return AlipayUtil.sandboxOrder(String.valueOf(amount),description);
//    }

//    @ApiOperation("微信支付-下单")
//    @GetMapping("/wx/createOrder")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "memberId", value = "会员Id",required = true),
//            @ApiImplicitParam(name = "amount", value = "金额",required = true),
//            @ApiImplicitParam(name = "description", value = "产品描述",required = true),
//    })
//    public String createOrderForWx(String memberId,Double amount,String description){
//      return WechatPayUtil.createAppOrder(amount,description);
//    }

    private LmsOrder createOrder(String memberId, String gradeId, Integer payType) {
        // 获取会员购买信息
        ClsMemberGrade grade = clsMemberGradeMapper.selectClsMemberGradeById(gradeId);
        if (grade == null) throw new RuntimeException("会员购买信息不存在");

        // 生成订单信息
        LmsOrder vo = new LmsOrder();
        vo.setOrderSn("wyd" + IdUtil.getSnowflakeNextIdStr());
        vo.setId(UUIDUtils.getUUID());
        vo.setSourceType(1);
        vo.setStatus(0);
        vo.setOrderType(0);
        vo.setPayType(payType);
//        vo.setNote(note);
        vo.setTotalAmount(grade.getDiscountPrice());
        vo.setPayAmount(vo.getTotalAmount());
        vo.setIntegrationAmount(BigDecimal.ZERO);
        vo.setUseIntegration(0L);

        vo.setMemberId(memberId);
        vo.setModifyTime(DateUtils.getNow());
        vo.setCreateTime(DateUtils.getNow());
//        vo.setPaymentTime(DateUtils.getNow());

        // TODO  新增明细 商品分类: 0: 会员充值，1：购买课程，2：老师批改作业
        LmsOrderItem item = new LmsOrderItem();
        item.setId(IdGen.randomLong());
        item.setOrderId(vo.getId());
        item.setOrderSn(vo.getOrderSn());
        item.setProductId(grade.getId());
//        item.setProductCategoryId(productCategoryId);
        item.setProductName(grade.getName());
        item.setProductPic(grade.getHeadImg());
        item.setProductPrice(vo.getTotalAmount());
        item.setGiftIntegration(0L);
        lmsOrderItemService.insertLmsOrderItem(item);
        orderService.insertLmsOrder(vo);

        return vo;
    }

}

